import React, { Component } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
// import ProTable from '@ant-design/pro-table';
// import { queryRule } from './service';
import { Divider, Button, Modal, Form, Input, Row, Col, Select, Radio, Table, Card, Icon, Popconfirm, message} from 'antd';
import { connect } from 'dva';
import copy from 'copy-to-clipboard';
import styles from './style.less';
import IconFont from '../../components/Icon';


import PublicTableWrapper from '@/components/TableForm'
// eslint-disable-next-line import/no-unresolved
import AddUser from './components/addUser'



const selectOptions = [
    {value: '西乡街道', key: '西乡街道'},
    {value: '宝安街道', key: '宝安街道'},
    {value: '龙岗街道', key: '龙岗街道'},
    {value: '南山街道', key: '南山街道'},
    {value: '龙华街道', key: '龙华街道'},
    {value: '罗湖街道', key: '罗湖街道'},
]

const children = []
selectOptions.forEach(v => {
    children.push(<Select.Option value={v.key} key={v.key}>{v.value}</Select.Option>)
})



// 重置密码
const ResetPwd = Form.create()(
    // eslint-disable-next-line react/prefer-stateless-function
    class extends React.Component {
        
        copyHandleClick = () => {  
            copy('123456789')
            message.success('复制成功！')
        }

        checkPsd2(rule, value, callback) {
            const password = this.props.form.getFieldValue('pwd1');
            if (password && password !== value) {
                callback(new Error('两次密码输入不一致！'));
            } else {
                callback();
            }
        }

        render() {
            const { visible, onCancel, onCreate, form, userName } = this.props
            const { getFieldDecorator } = form
            const formItemLayout = {
                labelCol: { span: 8 },
                wrapperCol: { span: 14 }
            }
            return (
                <Modal
                    visible={visible}
                    title="密码重置"
                    width='60%'
                    onCancel={onCancel}
                    onOk={onCreate}
                >
                    <Form style={{width: '80%', margin:'0 auto'}}>
                        <Row gutter={24}>
                            <Col span={24}>
                                <Form.Item label="账户名名称" {...formItemLayout}>
                                    <a>{userName}</a>
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="请输入新密码" {...formItemLayout} required={false}>
                                    {getFieldDecorator('pwd1', {
                                        rules: [
                                            { required: true, message: '请输入!'},
                                        ],
                                    })(<Input.Password placeholder="请输入" style={{width:'80%'}}/>)}
                                </Form.Item>
                            </Col>
                            <Col span={24}>
                                <Form.Item label="请输入新密码" {...formItemLayout} required={false}>
                                    {getFieldDecorator('pwd2', {
                                        rules: [
                                            { required: true, message: '请输入!'},
                                            { validator: (rule, value, callback) => { this.checkPsd2(rule, value, callback) } }
                                        ],
                                    })(<Input.Password placeholder="请输入" style={{width:'80%'}}/>)}
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                </Modal>
            )
        }
    }
)





@connect(({ usersystemdandtable }) => ({
    usersystemdandtable
}))

// eslint-disable-next-line react/prefer-stateless-function
class Management extends Component {
    state = {
        // 搜索表展开收起
        expand: false,

        // 密码重置弹窗
        resetPwdShow: false,
        // 密码重置对象
        resetPwdObject: {},
        // 密码重置用户
        resetUserName: '',

        // 表格
        tableLoading: false,
        dataSource: [],
        page: 1,
        pageSize: 10,
        search: {},
        totalCount: 1,
        columns: [
            {
                title: '管理员姓名',
                dataIndex: 'manage_name',
                width: 180,
            },
            {
                title: '账户名称',
                dataIndex: 'user_name',
                width: 180,
            },
            {
                title: '负责街道',
                dataIndex: 'manage_street',
            },
            {
                title: (<div>状态<i style={{marginLeft: '10px'}}><IconFont type="icon-loudou" /></i></div>),
                dataIndex: 'status',
                width: 180,
                render: (_, record) => {
                    if (record.status) {
                        return (<span style={{color: '#1890ff'}}>启用</span>)
                    }
                    return (<span style={{color: 'red'}}>禁用</span>)
                }
            },
            {
                title: '操作',
                dataIndex: 'option',
                valueType: 'option',
                width: 180,
                render: (_, record) => (
                <>
                    <a
                        onClick={() => this.resetPwd(_, record)}
                    >
                        密码重置
                    </a>
                    <Divider type="vertical" style={{margin:'0 10px'}}/>
                    <Popconfirm
                        title= {`你确定要${record.status ? '禁用' : '启用'}吗？`}
                        onConfirm={() => this.resetStatus(record)}
                        okText="是"
                        cancelText="否"
                    >
                        
                        {record.status ? <a>禁用</a> : <a>启用</a>}
                    </Popconfirm>
                </>
                ),
            },
        ],
    }

    // 初始化
    componentDidMount() {
        this.initfetch()
    }

    // 生成表头搜索
    getFields() {
        const formItemLayout = { labelCol: { span: 5 }, wrapperCol: { span: 14 } }
        const { getFieldDecorator } = this.props.form
        const count = !!this.state.expand;
        if ( count ) {
            return (
                <>
                    <Col span={8}>
                        <Form.Item label="管理员姓名" {...formItemLayout}>
                            {getFieldDecorator("manage_name")(
                                <Input placeholder="请输入" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="账户名称" {...formItemLayout}>
                            {getFieldDecorator("user_name")(
                                <Input placeholder="请输入" />
                            )}
                        </Form.Item>
                    </Col>
                    <Col span={8}>
                        <Form.Item label="负责街道" {...formItemLayout}>
                            {getFieldDecorator("manage_street")(
                                <Select placeholder="请选择">
                                    {children}
                                </Select>
                            )}
                        </Form.Item>
                    </Col>
                </>
            )
        } 
        return (
            <>
                <Col span={8}>
                    <Form.Item label="管理员姓名" {...formItemLayout}>
                        {getFieldDecorator("manage_name")(
                            <Input placeholder="请输入" />
                        )}
                    </Form.Item>
                </Col>
                <Col span={8}>
                    <Form.Item label="账户名称" {...formItemLayout}>
                        {getFieldDecorator("user_name")(
                            <Input placeholder="请输入" />
                        )}
                    </Form.Item>
                </Col>
            </>
        )
    }

    // 获取表格
    initfetch = () => {
        const { dispatch } = this.props
        const { page, pageSize, search } = this.state
        this.setState({
            tableLoading: true
        })
        dispatch({
            type: 'usersystemdandtable/fetch',
            payload: {
                limit: pageSize,
                offset: (page-1)*10,
                search
            }
        }).then(res => {
            if (res.status === 200) {
                this.setState({
                    totalCount: res.totalPageSize-1,
                    dataSource: res.tableListDataSource
                })
            }
            this.setState({
                tableLoading: false,
            })
        })
    }

    // 换页
    paginationChange = (page, pageSize) => {
        this.setState({
            page,
            pageSize
        })

        // 获取数据
        this.initfetch()
    }

    // 密码重置
    resetPwd = (_, record) => {
        this.setState({
            resetUserName: record.user_name,
            resetPwdShow: true,
            resetPwdObject: record
        })
    }

    handleCancel= () => {
        this.setState({
            resetPwdShow: false,
        })
    }

    // 重置密码确认
    resetPwdConfirm = () => {
        const { resetPwdObject } = this.state
        const { dispatch } = this.props
        const { form } = this.resetRef.props

        form.validateFields((err, values) => {
            if (err) {
                return;
            }
            values.id = resetPwdObject.id
            dispatch({
                type: 'usersystemdandtable/modifyPwd',
                payload: values
            }).then(res => {
                if (res === 200) {
                    message.success('成功')
                    this.initfetch()
                    this.handleCancel()
                }
            })
        })

        
    }
    
    // 状态更改
    resetStatus = record => {
        const { dispatch } = this.props
        dispatch({
            type: 'usersystemdandtable/modifyStatus',
            payload: {
                id: record.id
            }
        }).then(res => {
            if (res === 200) {
                this.initfetch()
            }
        })
    }

    resetFormRef = formRef => {
        this.resetRef = formRef
    }
    
    // 搜索表查询
    handleSearch = e => {
        const { home } = this.props
        let originallyArrary = [...home.users_system]
        e.preventDefault()
        this.props.form.validateFields((err, values) => {
            Object.keys(values).forEach(key => {
                if (values[key]) {
                    const newBlank = []
                    originallyArrary.forEach((val, index) => {
                        if (val[key].includes(values[key])) {
                            newBlank.push(originallyArrary[index])
                        }
                    })
                    originallyArrary = newBlank
                }
            })
            this.setState({
                dataSource: originallyArrary
            })
        })


    }

    // 搜索表重置
    handleReset = () => {
        this.props.form.resetFields()
    }

    // 收起展开
    toggle = () => {
        const { expand } = this.state
        this.setState({ expand: !expand })
    }

    render (){
        
        return (
            <PageHeaderWrapper title="街道管理员列表">
                <Card className={styles.proTable} bordered={false}>
                    <Form onSubmit={this.handleSearch} style={{padding: '12px 36px 0 36px'}} className={styles.tableSerech}>
                        <Row gutter={24}>
                            {this.getFields()}
                            <Col span={8}>
                                <Form.Item style={{display: 'flex' }}>
                                    <Button type="primary" htmlType="submit">
                                        查询
                                    </Button>
                                    <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                                        重置
                                    </Button>
                                    <a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
                                        {this.state.expand ? '收起' : '展开'} <Icon type={this.state.expand ? 'up' : 'down'} />
                                    </a>
                                </Form.Item>
                            </Col>
                        </Row>
                    </Form>
                    
                    <div className={styles.toolBarBtn}>
                        <AddUser 
                            create={this.initfetch}
                        />
                    </div>
                    <PublicTableWrapper 
                        loading={this.state.tableLoading}
                        columns={this.state.columns}
                        data={this.state.dataSource}
                        currentpageSize={this.state.pageSize}
                        total={this.state.totalCount}
                        paginationChange= {(page, pageSize) => this.paginationChange(page, pageSize)}
                    />
                </Card>

                <ResetPwd 
                    wrappedComponentRef={this.resetFormRef}
                    visible={this.state.resetPwdShow}
                    onCancel={this.handleCancel}
                    onCreate={this.resetPwdConfirm}
                    userName={this.state.resetUserName}
                />


            </PageHeaderWrapper>
        )
    }
}


const WrappedAdvancedSearchForm = Form.create()(Management);


// export default Management
export default WrappedAdvancedSearchForm